from django import forms
from django.forms import ValidationError


class ListField(forms.Field):
    # example = {
    #     '不传参': None,
    #     '传参': {
    #         '不是list': error,
    #         '是list': {
    #             '空list': data,
    #             '非空list': data
    #         }
    #     },
    # }

    empty_values = [None, '']
    cus_message = {
        'type': 'must be an array',
        'empty': 'length of array must more than 1'
    }

    def __init__(self, is_empty_list: bool = True, **kwargs):
        # is_empty:是否接受空列表

        super().__init__(**kwargs)  # 先继承init，再复写属性
        self.error_messages.update(self.cus_message)
        self.is_empty_list = is_empty_list

    def to_python(self, value):

        if value == None:  # 不传参
            return value
        if not isinstance(value, list):  # 传参，没传list
            raise forms.ValidationError(self.error_messages['type'], code='invalid')
        else:  # 传参，传的list
            if not value:  # 空列表
                if not self.is_empty_list:  # is_empty_list为false
                    raise ValidationError(self.error_messages['empty'], code='invalid')
            return value
